package edu.uoc.tfc.web.tags;



import java.util.ArrayList;
import java.util.List;

import javax.servlet.jsp.JspException;
import javax.servlet.jsp.JspWriter;

import edu.uoc.tfc.dto.security.OperationVO;



public class MenuTag extends EmktBaseTag
{

	private static final long serialVersionUID = 1L;


	private Object[] getParentsOperation (OperationVO[] operacions) throws Exception{
		List<OperationVO> pares = new ArrayList<OperationVO>();
		for(OperationVO op:operacions){
			if(op.getParent().intValue()==0){
				pares.add(op);
			}
		}
		return pares.toArray();
	}

	private Object[] getChildOperations (OperationVO[] operacions, int pareId) throws Exception{
		List<OperationVO> fills = new ArrayList<OperationVO>();		
		for(OperationVO op:operacions){
			if(op.getParent().intValue()==pareId){
				fills.add(op);
			}
		}
		return fills.toArray();
	}
		
	@Override
	public int doStartTag() throws JspException
	{
		OperationVO[] operacions = (OperationVO[]) 
				this.pageContext.getSession().getAttribute("menu");
		
		try{
			JspWriter out = this.pageContext.getOut();
			Object[] opsPare = getParentsOperation(operacions);
			
			for (Object pare:opsPare){
				OperationVO pareVO = (OperationVO)pare;
				Object[] opsFills = getChildOperations(operacions, pareVO.getId().intValue());
				
				out.write("<li class=\"dropdown hide\" style=\"display: list-item; \">");
				out.write(
						"<a class=\"dropdown-toggle\" data-toggle=\"dropdown\" href=\"#\">" + 
								this.getMessage(pareVO.getName(), null)  + 
						" <b class=\"caret\"></b></a>");
				out.write("<ul id=\"menu" + pareVO.getId() + "\" class=\"dropdown-menu\">");
							
				
				for(Object oper:opsFills){
					OperationVO op = (OperationVO)oper;
					out.write("<li>");
					out.write(
							"<a href=\"#\" class=\"emkt-ajax\" "
							+ "data-target-div=\"content\" "
							+ "data-service-url=\"" + super.getContextPath()
							+ "\" data-operation-url=\"" + op.getUrl()
							+ "\" >"
							+ this.getMessage(op.getName(), null) 
							+ "</a>");		
					out.write("</li>");
				}	
				out.write("</ul>");
				out.write("</li>");				
			}
			
		}catch (Exception e){
			throw new JspException();
		}
		return SKIP_BODY;
	}


	public int doEndTag() {
        return EVAL_PAGE;
    }

}
